﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class EmployeeDA : IEmployeeDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string DEPARTMENT_ID = "@DEPARTMENT_ID";
        private string EMPLOYEE_ID = "@EMPLOYEE_ID";
        private string EMPLOYEE_NAME = "@EMPLOYEE_NAME";
        private string ENTRANT_DATE = "@ENTRANT_DATE";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string MOBILE_PHONE = "@MOBILE_PHONE";
        private string POSITION = "@POSITION";
        private string REMARK = "@REMARK";
        private string SEX = "@SEX";
        private string SQL_CHECK_EMPLOYEE_ID_UNIQUE = " SELECT COUNT(1) FROM @_@EMPLOYEE WHERE EMPLOYEE_ID = @EMPLOYEE_ID ";
        private string SQL_DELETE_EMPLOYEE = " DELETE FROM @_@EMPLOYEE WHERE EMPLOYEE_ID = @EMPLOYEE_ID ";
        private string SQL_INSERT_EMPLOYEE = "INSERT INTO @_@EMPLOYEE(WH_ID,EMPLOYEE_ID,EMPLOYEE_NAME,SEX,POSITION,DEPARTMENT_ID,MOBILE_PHONE,ENTRANT_DATE,REMARK,IS_ACTIVE,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE)VALUES(@WH_ID,@EMPLOYEE_ID,@EMPLOYEE_NAME,@SEX,@POSITION,@DEPARTMENT_ID,@MOBILE_PHONE,@ENTRANT_DATE,@REMARK,@IS_ACTIVE,@CREATED_BY,GETDATE(),@UPDATED_BY,GETDATE())";
        private string SQL_SELECT_ALL_EMPLOYEE = "SELECT E.ROWID,E.WH_ID,E.EMPLOYEE_ID,E.EMPLOYEE_NAME,E.SEX,CASE E.SEX WHEN 'M' THEN '男' WHEN 'F' THEN '女' END AS SEX_DESCR,E.POSITION,E.DEPARTMENT_ID,E.MOBILE_PHONE,CONVERT(VARCHAR(20),E.ENTRANT_DATE,23) AS ENTRANT_DATE,E.REMARK,E.IS_ACTIVE,E.TS,E.CREATED_BY,CONVERT(VARCHAR(20),E.CREATED_DATE,23) AS CREATED_DATE,E.UPDATED_BY,E.UPDATED_DATE,D.DESCR AS DEPARTMENT_DESCR,SCD.DESCRIPTION AS POSITION_DESCR FROM @_@EMPLOYEE E LEFT JOIN @_@DEPARTMENT D ON D.DEPARTMENT_ID = E.DEPARTMENT_ID LEFT JOIN @_@SYS_CODE_DETAIL SCD ON SCD.SYS_CODE_TYPE = 'EmployeePosition' AND SCD.SYS_CODE = E.POSITION ";
        private string SQL_UPDATE_EMPLOYEE = " UPDATE @_@EMPLOYEE SET WH_ID = @WH_ID,EMPLOYEE_NAME = @EMPLOYEE_NAME,SEX = @SEX,POSITION = @POSITION,DEPARTMENT_ID = @DEPARTMENT_ID,MOBILE_PHONE = @MOBILE_PHONE, ENTRANT_DATE = @ENTRANT_DATE,REMARK = @REMARK,IS_ACTIVE =@IS_ACTIVE,UPDATED_BY = @UPDATED_BY,UPDATED_DATE = GETDATE() WHERE EMPLOYEE_ID = @EMPLOYEE_ID";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckEmployeeIDUnique(string employeeID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_EMPLOYEE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckEmployeeIDUnique(DataBase dataBase, DbTransaction tran, string employeeID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_EMPLOYEE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteEmployee(List<string> employeeID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < employeeID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteEmployee(DataBase dataBase, DbTransaction tran, List<string> employeeID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < employeeID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllEmployee(string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllEmployee(DataBase dataBase, DbTransaction tran, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public EmployeeInfo GetEmployeeByID(string employeeID, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID) + " WHERE E.EMPLOYEE_ID = @EMPLOYEE_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID), new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            EmployeeInfo employeeInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    employeeInfo = new EmployeeInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["EMPLOYEE_ID"].ToString(), reader["EMPLOYEE_NAME"].ToString(), reader["SEX"].ToString(), reader["POSITION"].ToString(), reader["DEPARTMENT_ID"].ToString(), reader["MOBILE_PHONE"].ToString(), reader["ENTRANT_DATE"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return employeeInfo;
        }

        public EmployeeInfo GetEmployeeByID(DataBase dataBase, DbTransaction tran, string employeeID, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID) + " WHERE E.EMPLOYEE_ID = @EMPLOYEE_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EMPLOYEE_ID", employeeID), new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            EmployeeInfo employeeInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                employeeInfo = new EmployeeInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["EMPLOYEE_ID"].ToString(), reader["EMPLOYEE_NAME"].ToString(), reader["SEX"].ToString(), reader["POSITION"].ToString(), reader["DEPARTMENT_ID"].ToString(), reader["MOBILE_PHONE"].ToString(), reader["ENTRANT_DATE"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return employeeInfo;
        }

        public DataSet GetEmployeeByQueryList(List<string> sqlWhere, EmployeeQueryEntity employeeQuery, string whLoginID, PubParasInfo pubParasInfo)
        {
            string temp = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!employeeQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, employeeQuery.CurrentPage, employeeQuery.PageSize, employeeQuery.SortField, employeeQuery.SortDirection).Replace("@LANGUAGE", "''" + pubParasInfo.UserLanguage + "''");
            }
            else
            {
                temp = temp.Replace("@LANGUAGE", "'" + pubParasInfo.UserLanguage + "'");
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetEmployeeByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, EmployeeQueryEntity employeeQuery, string whLoginID, PubParasInfo pubParasInfo)
        {
            string temp = this.SQL_SELECT_ALL_EMPLOYEE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!employeeQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, employeeQuery.CurrentPage, employeeQuery.PageSize, employeeQuery.SortField, employeeQuery.SortDirection).Replace("@LANGUAGE", "''" + pubParasInfo.UserLanguage + "''");
            }
            else
            {
                temp = temp.Replace("@LANGUAGE", "'" + pubParasInfo.UserLanguage + "'");
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertEmployee(EmployeeInfo employeeInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    employeeInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Employee_Parameters(employeeInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertEmployee(DataBase dataBase, DbTransaction tran, EmployeeInfo employeeInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    employeeInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Employee_Parameters(employeeInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_Employee_Parameters(EmployeeInfo employeeInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.EMPLOYEE_ID, SqlDbType.VarChar, 50), new SqlParameter(this.EMPLOYEE_NAME, SqlDbType.VarChar, 100), new SqlParameter(this.SEX, SqlDbType.VarChar, 1), new SqlParameter(this.POSITION, SqlDbType.VarChar, 30), new SqlParameter(this.DEPARTMENT_ID, SqlDbType.VarChar, 100), new SqlParameter(this.MOBILE_PHONE, SqlDbType.VarChar, 30), new SqlParameter(this.ENTRANT_DATE, SqlDbType.VarChar, 30), new SqlParameter(this.REMARK, SqlDbType.VarChar, 300), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 30), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 30) };
            if (!string.IsNullOrEmpty(employeeInfo.WhID))
            {
                paramArray[0].Value = employeeInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = employeeInfo.EmployeeID;
            if (!string.IsNullOrEmpty(employeeInfo.EmployeeName))
            {
                paramArray[2].Value = employeeInfo.EmployeeName;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.Sex))
            {
                paramArray[3].Value = employeeInfo.Sex;
            }
            else
            {
                paramArray[3].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.Position))
            {
                paramArray[4].Value = employeeInfo.Position;
            }
            else
            {
                paramArray[4].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.DepartmentID))
            {
                paramArray[5].Value = employeeInfo.DepartmentID;
            }
            else
            {
                paramArray[5].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.MobilePhone))
            {
                paramArray[6].Value = employeeInfo.MobilePhone;
            }
            else
            {
                paramArray[6].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.EntrantDate.ToString()))
            {
                paramArray[7].Value = employeeInfo.EntrantDate;
            }
            else
            {
                paramArray[7].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.Remark))
            {
                paramArray[8].Value = employeeInfo.Remark;
            }
            else
            {
                paramArray[8].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.IsActive))
            {
                paramArray[9].Value = employeeInfo.IsActive;
            }
            else
            {
                paramArray[9].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.CreatedBy))
            {
                paramArray[10].Value = employeeInfo.CreatedBy;
            }
            else
            {
                paramArray[10].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(employeeInfo.UpdatedBy))
            {
                paramArray[11].Value = employeeInfo.UpdatedBy;
                return paramArray;
            }
            paramArray[11].Value = DBNull.Value;
            return paramArray;
        }

        public int UpdateEmployee(EmployeeInfo employeeInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    employeeInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Employee_Parameters(employeeInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateEmployee(DataBase dataBase, DbTransaction tran, EmployeeInfo employeeInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    employeeInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Employee_Parameters(employeeInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_EMPLOYEE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

